package com.demo.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * file upload controller
 * 
 * @author tao
 *
 */
@Controller
@RequestMapping("/file")
public class FileUploadController {
	/**
	 * file save path
	 */
	@Value("${file.resource.path}")
	private String filepath;

	/**
	 * 访问了路径
	 * 
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload(ModelMap modelMap) {
		modelMap.put("title", "");
		return "fileupload";
	}

	@RequestMapping(value = "/uploadBatch", method = RequestMethod.GET)
	public String uploadBatch(ModelMap modelMap) {
		modelMap.put("title", "");
		return "fileuploadBatch";
	}

	/**
	 * upload file
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public String fileUpload(@RequestParam("file") MultipartFile file, ModelMap modelMap) {
		String msg = "";
		if (!file.isEmpty()) {
			try {
				// 这里只是简单例子，文件直接输出到项目路径下。
				// 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
				// 还有关于文件格式限制、文件大小限制，详见：中配置。
				BufferedOutputStream out = new BufferedOutputStream(
						new FileOutputStream(new File(filepath + "/" + file.getOriginalFilename())));
				out.write(file.getBytes());
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				msg = "上传失败," + e.getMessage();
				modelMap.put("title", msg);
			} catch (IOException e) {
				e.printStackTrace();
				msg = "上传失败," + e.getMessage();
				modelMap.put("title", msg);
			}
			msg = "上传成功";
		} else {
			msg = "上传失败，因为文件是空的.";
		}

		modelMap.put("title", "上传成功");
		return "fileupload";
	}

	/**
	 * multipart files upload
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
	public String batchUpload(HttpServletRequest request, ModelMap modelMap) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					stream = new BufferedOutputStream(
							new FileOutputStream(new File(filepath + "/" + file.getOriginalFilename())));
					stream.write(bytes);
					stream.close();
				} catch (Exception e) {
					stream = null;
					modelMap.put("title", "You failed to upload " + i + " => " + e.getMessage());
				}
			} else {
				modelMap.put("title", "You failed to upload " + i + " because the file was empty.");
			}
		}

		modelMap.put("title", "batch upload successful");

		return "fileuploadBatch";
	}
}
